var express = require("express");
var router = express.Router();
var db = require("../db/index");

// 添加社团
router.post('/add', function (req, res) {
  let {title, creationTime} = req.body;
  db.query(`SELECT * FROM society WHERE title = '${title}'`, function (err, rows) {
    if (rows.length > 0) {
      res.send({
        code: 10008,
        message: '该社团名已存在'
      })
    } else {
      db.query(`INSERT INTO society SET ?`, {title, creationTime, haveAdmin: 0}, function (err) {
        if (err) {
          res.send({
            code: 10004,
            message: '添加新社团失败'
          })
        } else {
          res.send({
            code: 200,
            message: '添加新社团成功'
          })
        }
      })
    }
  })
})

//// 获取所有社团信息
router.get('/getInfo', function (req, res) {
  let {pageNo, limit} = req.query;
  let start = (pageNo - 1) * limit;
  db.query(`SELECT s.*,COUNT(a.id) AS total 
            FROM account a RIGHT JOIN society s ON s.id = a.society_id 
            GROUP BY s.id 
            order by s.creationTime DESC 
            LIMIT ${start},${limit}`, function (err, rows) {
    if (!err) {
      db.query(`SELECT COUNT(*) AS count FROM society`, function (err2, societyNum) { // 获取社团总数
        res.send({
          code: 200,
          message: '获取成功',
          data: {
            rows,
            societyNum: societyNum[0].count
          }
        })
      })

    } else {
      res.send({
        code: 10006,
        message: '社团数据获取失败，请尝试刷新'
      })
    }
  })
})

// 获取社团所有社员信息
router.get('/member/info', function (req, res) {
  let {society_id, pageNo, limit} = req.query;
  let start = (pageNo - 1) * limit;
  let sql = `SELECT * FROM account WHERE society_id = ${society_id} ORDER BY id LIMIT ${start},${limit}`
  db.query(sql,async function (err, rows) {
    let list = await Promise.all(rows.map(item=>{
      return new Promise(resolve => {
        db.query(`SELECT count(id) as total FROM activity_join WHERE user_id=${item.id}`,function (err,[{total}]) {
          item.joinActivityCount=total
          resolve(item)
        })
      })
    }))
    db.query(`SELECT count(id) as total FROM account WHERE society_id = ${society_id}`, function (err2, [{total}]) {
      res.send({
        code: 200,
        message: err || err2 || 'OK',
        list,
        total
      })
    })
  })
})

// 获取单个社团信息
router.get('/getSocietyInfo', function (req, res) {
  let {society_id} = req.query;
  db.query(`SELECT s.*,COUNT(a.id) AS total,
            (SELECT COUNT(id) FROM activity WHERE society_id = ${society_id}) as activity_count,
            (SELECT COUNT(id) FROM article WHERE society_id = ${society_id}) as article_count
            FROM society s LEFT JOIN account a ON s.id = a.society_id
            WHERE s.id = ${society_id}`, function (err, rows) {

    if (rows.length > 0 && !err) {
      res.send({
        code: 200,
        message: '获取成功',
        society: rows[0]
      })
    } else {
      res.send({
        code: 10006,
        message: '社团数据获取失败，请尝试刷新'
      })
    }
  })
})

// 根据id删除社团
router.post('/delete', function (req, res) {
  let ids = req.body.ids;
  db.query(`DELETE FROM society WHERE id in (${ids})`, function (err) {
    if (!err) {
      res.send({
        code: 200,
        message: '删除成功'
      })
    } else {
      res.send({
        code: 10011,
        message: '删除失败，请稍候重试！'
      })
    }
  })
})

// 退出社团
router.get('/quit', function (req, res) {
  let {user_id} = req.query;
  db.query(`UPDATE account SET society_id = ? WHERE id = ?`, [null, user_id], function (err) {
    if (err) {
      res.send({
        code: 20006,
        message: '更新失败'
      })
    } else {
      res.send({
        code: 200,
        message: '成功'
      })
    }
  })
})

// 申请加入社团
router.post('/join', function (req, res) {
  let {user_id, society_id, content, apply_time} = req.body;
  db.query(`INSERT INTO apply SET ?`, {user_id, society_id, content, apply_time}, function (err) {
    if (err) {
      res.send({
        code: 10014,
        message: '失败'
      })
    } else {
      res.send({
        code: 200,
        message: '成功'
      })
    }
  })
})
// 查看申请
router.get('/join/history', function (req, res) {
  let {user_id} = req.query;
  db.query(`SELECT a.*,s.title AS society_title FROM apply a LEFT JOIN society s ON a.society_id = s.id WHERE a.user_id = ${user_id}`, function (err, rows) {
    if (!err) {
      res.send({
        code: 200,
        message: '成功',
        list: rows || []
      })
    } else {
      res.send({
        code: 10034,
        message: '失败'
      })
    }
  })
})
// 撤销申请
router.get('/join/undo', function (req, res) {
  let {id} = req.query;
  db.query(`DELETE FROM apply WHERE id =${id}`, function (err) {
    if (!err) {
      res.send({
        code: 200,
        message: '成功',
      })
    } else {
      res.send({
        code: 10035,
        message: '失败'
      })
    }
  })
})
module.exports = router;